package com.yantong.service.impl;

import com.yantong.constant.AdvertShowState;
import com.yantong.mapper.AdvertMapper;
import com.yantong.mapper.BaTypeMapper;
import com.yantong.mapper.MemberAggregationMapper;
import com.yantong.mapper.MemberMapper;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.AdvertVo;
import com.yantong.utils.PageUtils;
import com.yantong.pojo.vo.AdvertVos;
import com.yantong.service.AdvertService;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kanghaixin
 * @date 2018/8/29.13:45
 */
@Service
public class AdvertServiceImpl implements AdvertService {
    @Autowired
    private AdvertMapper advertMapper;
    @Autowired
    private BaTypeMapper baTypeMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberAggregationMapper memberAggregationMapper;


    private static final Logger logger = LoggerFactory.getLogger(AdvertServiceImpl.class);

    @Override
    public PageUtils<Advert> listAdverts(Integer baTypeId, String advName, Long centreId,Long teamId, int offset, int limit) {
        logger.info("listAdverts baTypeId:{},advName:{}", baTypeId, advName);
        PageUtils<Advert> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(4);

        if (StringUtils.isNotEmpty(advName)) {
            params.put("advName", advName);
        }
        if (baTypeId != null) {
            params.put("baTypeId", baTypeId);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if(teamId != null){
            params.put("teamId", teamId);
        }
        int total = advertMapper.countByParams(params);
        if (total > 0) {
            List<Advert> list = advertMapper.listByParams(params, new RowBounds(offset, limit));
            list.stream().filter(advert -> advert.getType() != null).forEach(advert -> {
                BaType baType = baTypeMapper.selectByPrimaryKey(Long.parseLong(advert.getType().toString()));
                if (baType != null) {
                    advert.setTypeName(baType.getName());
                }
            });
            pageUtils.setRows(list);
            pageUtils.setTotal(total);
        }
        return pageUtils;
    }

    @Override
    public int disableShow(Long advertId) {
        if (advertId == null) {
            return 0;
        }
        Advert advert = new Advert();
        advert.setId(advertId);
        advert.setEnabled(AdvertShowState.disbaled);
        return advertMapper.updateByPrimaryKeySelective(advert);
    }

    @Override
    public int enableShow(Long advertId) {
        if (advertId == null) {
            return 0;
        }
        Advert advert = new Advert();
        advert.setId(advertId);
        advert.setEnabled(AdvertShowState.enabled);
        return advertMapper.updateByPrimaryKeySelective(advert);
    }

    @Override
    public int removeAdvert(Long advertId) {
        if (advertId == null) {
            return 0;
        }
        Advert advert = new Advert();
        advert.setId(advertId);
        advert.setDeleted(1);
        return advertMapper.updateByPrimaryKeySelective(advert);
    }

    @Override
    public int batchRemove(List<Long> advertIds) {
        if (CollectionUtils.isEmpty(advertIds)) {
            return 0;
        }
        return advertMapper.batchRemove(advertIds);
    }

    @Override
    public int saveAdvert(Advert advert) {
        if (advert == null) {
            return 0;
        }
        return advertMapper.insertSelective(advert);
    }

    /**
     * 保存广告信息
     *
     * @param advert
     * @return
     */
    @Override
    public int addAdvert(AdvertVos advert) {
        if (advert == null) {
            return 0;
        }
        return advertMapper.saveAdvert(advert);
    }

    ;

    @Override
    public int updateAdvert(Advert advert) {
        if (advert == null || advert.getId() == null) {
            return 0;
        }
        if (advert.getEnabled() == null) {
            advert.setEnabled(0);
        }
        return advertMapper.updateByPrimaryKeySelective(advert);
    }

    @Override
    public Advert getByKey(Long id) {
        if (id == null) {
            return null;
        }
        Advert advert = advertMapper.selectByPrimaryKey(id);
        //时间处理
        if (advert.getUpStartTime() != null) {
            advert.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(advert.getUpStartTime()));
        }
        if (advert.getUpEndTime() != null) {
            advert.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(advert.getUpEndTime()));
        }
        return advert;
    }

    @Override
    public List<Advert> listAdverts(Integer type, Long centreId) {
        if (type == null || centreId == null) {
            logger.info("type or centreId is null,get adverts failed!");
            return null;
        }
        AdvertExample example = new AdvertExample();
        AdvertExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type)
                .andCentreIdEqualTo(centreId)
                .andDeletedEqualTo(0)
                .andEnabledEqualTo(1);
        example.setOrderByClause("displayorder desc");
        example.setNewDate(new Date());
        return advertMapper.selectByExample(example);
    }

    @Override
    public List<AdvertVo> listAdverts(BannersReqDto reqDto) {
        if (
                StringUtils.isEmpty(reqDto.getTop() + "") ||
                        StringUtils.isEmpty(reqDto.getType())
                ) {
            logger.info("请求参数为空!");
            return null;
        }
        if (null == reqDto.getFlag()) {
            reqDto.setFlag(0);
        }
        if(ValidateUtil.isNotEmptyString(reqDto.getTeamSeqId())){
            MemberAggregation memberAggregation = memberAggregationMapper.queryByCode(reqDto.getTeamSeqId());
            if(null != memberAggregation && null != memberAggregation.getMid()){
                Member shopMember = memberMapper.selectByPrimaryKey(memberAggregation.getMid());
                if(null != shopMember && null != shopMember.getCentreId()){
                    reqDto.setCenterId(shopMember.getCentreId().toString());
                }
            }
        }
        return advertMapper.selectAdvertsList(reqDto);
    }
}
